using Unity.Burst;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.Rendering;
using UnityEngine;
using Random = Unity.Mathematics.Random;

namespace Tanks.Step6
{
    public partial struct TankSpawningSystem : ISystem
    {
        [BurstCompile]
        public void OnCreate(ref SystemState state)
        {
            state.RequireForUpdate<Execute.TankSpawning>();
            state.RequireForUpdate<Config>();
        }

        [BurstCompile]
        public void OnUpdate(ref SystemState state)
        {
            state.Enabled = false; //只执行一次
            var config = SystemAPI.GetSingleton<Config>();
            var random = new Random(123);

            //创建一个用于Query颜色组件的Mask
            var query = SystemAPI.QueryBuilder().WithAll<URPMaterialPropertyBaseColor>().Build();
            var queryMask = query.GetEntityQueryMask();

            //使用ecb实例化
            var ecb = new EntityCommandBuffer(Allocator.Temp);
            var tanks = new NativeArray<Entity>(config.TankCount, Allocator.Temp);
            ecb.Instantiate(config.TankPrefab, tanks);

            //使用ecb设置颜色值
            foreach (var tank in tanks)
            {
                ecb.SetComponentForLinkedEntityGroup(tank, queryMask, new URPMaterialPropertyBaseColor()
                {
                    Value = RandomColor(ref random),
                });
            }

            //执行ecb中的命令
            ecb.Playback(state.EntityManager);
        }


        static float4 RandomColor(ref Random random)
        {
            //随机颜色生成原理:
            //https://martin.ankerl.com/2009/12/09/how-to-create-random-colors-programmatically/
            var hue = (random.NextFloat() + 0.618034005f) % 1;
            return (Vector4)Color.HSVToRGB(hue, 1f, 1f); //色调, 饱和度, 明度
        }
    }
}